const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const path = require('path');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 用户登录
router.get('/wxLogin/:code', async (req, res) => {
  try {
    const { code } = req.params;
    // 这里需要调用微信接口获取openid
    const openid = await getOpenidFromWx(code);
    
    let user = await User.findOne({ openid });
    if (!user) {
      user = await User.create({ openid });
    }

    const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET);
    res.json({
      code: 200,
      message: '登录成功',
      data: { token, user }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '登录失败',
      data: null
    });
  }
});

// 获取用户信息
router.get('/getuserInfo', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId);
    res.json({
      code: 200,
      message: '成功',
      data: user
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取用户信息失败',
      data: null
    });
  }
});

// 更新用户信息
router.post('/updateUser', auth, async (req, res) => {
  try {
    const { nickname, avatar } = req.body;
    const user = await User.findByIdAndUpdate(
      req.user.userId,
      { nickname, avatar },
      { new: true }
    );
    res.json({
      code: 200,
      message: '更新成功',
      data: user
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '更新用户信息失败',
      data: null
    });
  }
});

// 上传文件
router.post('/fileUpload', auth, upload.single('file'), async (req, res) => {
  try {
    const file = req.file;
    res.json({
      code: 200,
      message: '上传成功',
      data: {
        url: `/uploads/${file.filename}`
      }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '上传失败',
      data: null
    });
  }
});

// 获取用户地址列表
router.get('/userAddress/auth/findUserAddressList', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId);
    res.json({
      code: 200,
      message: '成功',
      data: user.addresses
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取地址列表失败',
      data: null
    });
  }
});

// 添加用户地址
router.post('/userAddress/auth/save', auth, async (req, res) => {
  try {
    const address = req.body;
    const user = await User.findById(req.user.userId);
    user.addresses.push(address);
    await user.save();
    res.json({
      code: 200,
      message: '添加成功',
      data: user.addresses
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '添加地址失败',
      data: null
    });
  }
});

// 更新用户地址
router.post('/userAddress/auth/update', auth, async (req, res) => {
  try {
    const { addressId, ...address } = req.body;
    const user = await User.findById(req.user.userId);
    const index = user.addresses.findIndex(addr => addr._id.toString() === addressId);
    if (index > -1) {
      user.addresses[index] = { ...user.addresses[index].toObject(), ...address };
      await user.save();
      res.json({
        code: 200,
        message: '更新成功',
        data: user.addresses
      });
    } else {
      res.status(404).json({
        code: 404,
        message: '地址不存在',
        data: null
      });
    }
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '更新地址失败',
      data: null
    });
  }
});

// 删除用户地址
router.delete('/userAddress/auth/remove/:addressId', auth, async (req, res) => {
  try {
    const { addressId } = req.params;
    const user = await User.findById(req.user.userId);
    user.addresses = user.addresses.filter(addr => addr._id.toString() !== addressId);
    await user.save();
    res.json({
      code: 200,
      message: '删除成功',
      data: user.addresses
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '删除地址失败',
      data: null
    });
  }
});

// 设置默认地址
router.get('/userAddress/auth/setDefaultAddress/:addressId', auth, async (req, res) => {
  try {
    const { addressId } = req.params;
    const user = await User.findById(req.user.userId);
    user.addresses = user.addresses.map(addr => ({
      ...addr.toObject(),
      isDefault: addr._id.toString() === addressId
    }));
    await user.save();
    res.json({
      code: 200,
      message: '设置成功',
      data: user.addresses
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '设置默认地址失败',
      data: null
    });
  }
});

module.exports = router; 